import { ref, onUnmounted } from 'vue'

import { useIntersectionObserver, useIntervalFn } from '@vueuse/core'

export function useObserver (apiFn) {
  const target = ref(null)
  const { stop } = useIntersectionObserver(
    target,
    ([{ isIntersecting }], observerElement) => {
    // targetIsVisible.value = isIntersecting
      console.log(isIntersecting)
      // 判断是不是懒加载
      if (isIntersecting) {
      // 是懒加载调用接口
        apiFn()
        //   停止懒加载
        stop()
      }
    }, { threshold: 0 }
  )

  return { target }
}

/**
 *
 * @param {*} time 倒计时时间（60）
 */
export function useCountDown (time) {
  /**
     * pause 停止
     * resume 开始
     */
  const count = ref(0)
  const { pause, resume } = useIntervalFn(() => {
    /* your function */
    // console.log(count.value)
    count.value--
    if (count.value <= 0) {
      pause()
    }
  }, 1000, { immediate: false })

  const start = () => {
    // 每次开始判断如果是0，重新开始
    if (count.value === 0) {
      count.value = time
    }
    // 开始倒计时
    resume()
  }
  // 组件销毁时，清除定时器
  onUnmounted(() => {
    pause()
  })
  // 暴露=》数据和方法
  return { count, start, pause }
}
